package com.sskj.uboex.ui.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.CommonUtil;
import com.sskj.uboex.R;
import com.sskj.uboex.bean.Banner;
import com.sskj.uboex.bean.NoticeList;
import com.sskj.uboex.bean.SlideCoinBean;
import com.sskj.uboex.component.DaggerUserDataComponent;
import com.sskj.uboex.http.HttpConfig;
import com.sskj.uboex.presenter.HangqingFragmentPresenter;
import com.youth.banner.loader.ImageLoader;
import com.youth.banner.loader.ImageLoaderInterface;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.APP_HANGQING)
public class HangqingFragment extends BaseFragment<HangqingFragmentPresenter> {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.llSelfChoose)
    LinearLayout llSelfChoose;
    @BindView(R.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R.id.llMsg)
    LinearLayout llMsg;
    //    @BindView(R.id.recyclerViewSlide)
//    RecyclerView recyclerViewSlide;
    @BindView(R.id.banner)
    com.youth.banner.Banner banner;
    //    @BindView(R.id.bannerCoin)
//    com.youth.banner.Banner bannerCoin;
    @BindView(R.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R.id.tv_show_position)
    TextView tvShowPosition;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.viewDot0)
    View viewDot0;
    @BindView(R.id.viewDot1)
    View viewDot1;
    @BindView(R.id.viewDot2)
    View viewDot2;
    @BindView(R.id.btBuy)
    Button btBuy;
    @BindView(R.id.etNum)
    EditText etNum;
    @BindView(R.id.tvRMB)
    TextView tvRMB;
    private SlimAdapter<StockCoinBean> slimAdapter;
    private HashMap<String, Integer> coinMap;
    private String[] valueUrl;
    private List<String> images = new ArrayList<>();
    private boolean isBannerShow = false;
    private Disposable noticeDispo;
    private NoticeList noticeList;
    private Map<String, Disposable> timeMap = new HashMap<>();
    private SlideCoinBean slideCoinBean;
    private int changePos;
    HashMap<SlideCoinBean, View> slideCoinBeanViewHashMap = new HashMap<>();
    private ArrayList<SlideCoinBean> slideCoinBeans;
    private HashMap<View, SlideCoinBean> viewSlideCoinBeanHashMap = new HashMap<>();
    HashMap<Integer, View> integerViewHashMap = new HashMap<>();
    @Inject
    UserViewModel userViewModel;
    private UserData userData;


    @Override
    protected int getLayoutId() {
        return R.layout.app_fragment_hangqing;
    }

    @Override
    public HangqingFragmentPresenter getPresenter() {
        return new HangqingFragmentPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        ClickUtil.click(llSelfChoose, () -> {
            ARouter.getInstance().build(RConfig.APP_SELF_CHOOSE).navigation();
        });
        ClickUtil.click(llMsg, () -> {
            ARouter.getInstance().build(RConfig.APP_MSG).withString(Constans.TYPE, "2").navigation();
        });
        ClickUtil.click(btBuy, () -> {
            if (userData == null) {
                ToastUtil.showShort("请先登录");
                return;
            }
            if (TextUtils.isEmpty(etNum.getText())) {
                ToastUtil.showShort("请输入购买数量");
                return;
            }
            ARouter.getInstance().build(RConfig.APP_LINK_WEB)
                    .withString(Constans.URL, HttpConfig.BASE_URL + HttpConfig.ONE_PAY + "?fee=" + etNum.getText().toString())
                    .navigation();
        });
        initRecy();
        initRecySlide();
        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                mPresenter.getData("USDT", false);
            }
        });
        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 30);
            textView.setTextColor(getResources().getColor(R.color.app_575));
            return textView;
        });

    }

    private void initRecySlide() {
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return 3;
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                View inflate;
                if (integerViewHashMap.get(position) == null) {
                    inflate = LayoutInflater.from(getActivity()).inflate(R.layout.app_include_slide_coin, null, false);
                    container.addView(inflate);
                    integerViewHashMap.put(position, inflate);
                } else {
                    inflate = integerViewHashMap.get(position);
                }

                return inflate;
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                viewDot0.setBackground(ContextCompat.getDrawable(App.INSTANCE, position == 0 ? R.drawable.app_shape_dot_select : R.drawable.app_shape_dot_unselect));
                viewDot1.setBackground(ContextCompat.getDrawable(App.INSTANCE, position == 1 ? R.drawable.app_shape_dot_select : R.drawable.app_shape_dot_unselect));
                viewDot2.setBackground(ContextCompat.getDrawable(App.INSTANCE, position == 2 ? R.drawable.app_shape_dot_select : R.drawable.app_shape_dot_unselect));
                super.onPageSelected(position);
            }
        });

    }

    private void updateSlideCoin(SlideCoinBean data, View view) {
        TextView tvCoinTypeFirst = view.findViewById(R.id.tvCoinTypeFirst);
        TextView tvCoinUSDTFirst = view.findViewById(R.id.tvCoinUSDTFirst);
        TextView tvCoinRateFirst = view.findViewById(R.id.tvCoinRateFirst);
        TextView tvCoinTypeSecond = view.findViewById(R.id.tvCoinTypeSecond);
        TextView tvCoinUSDTSecond = view.findViewById(R.id.tvCoinUSDTSecond);
        TextView tvCoinRateSecond = view.findViewById(R.id.tvCoinRateSecond);
        TextView tvCoinTypeThird = view.findViewById(R.id.tvCoinTypeThird);
        TextView tvCoinUSDTThird = view.findViewById(R.id.tvCoinUSDTThird);
        TextView tvCoinRateThird = view.findViewById(R.id.tvCoinRateThird);

        tvCoinTypeFirst.setText(data.getTypeFirst());
        tvCoinUSDTFirst.setText(data.getUsdtFirst());
        tvCoinRateFirst.setText(data.getRateFirst());
        tvCoinTypeSecond.setText(data.getTypeSecond());
        tvCoinUSDTSecond.setText(data.getUsdtSecond());
        tvCoinRateSecond.setText(data.getRateSecond());
        tvCoinTypeThird.setText(data.getTypeThird());
        tvCoinUSDTThird.setText(data.getUsdtThird());
        tvCoinRateThird.setText(data.getRateThird());

        tvCoinRateFirst.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpFirst() ? R.color.app_f53 : R.color.app_05c));
        tvCoinUSDTFirst.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpFirst() ? R.color.app_f53 : R.color.app_05c));
        tvCoinRateSecond.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpSecond() ? R.color.app_f53 : R.color.app_05c));
        tvCoinUSDTSecond.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpSecond() ? R.color.app_f53 : R.color.app_05c));
        tvCoinRateThird.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpThird() ? R.color.app_f53 : R.color.app_05c));
        tvCoinUSDTThird.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUpThird() ? R.color.app_f53 : R.color.app_05c));
    }

    @Override
    public void initData() {
        coinMap = new HashMap<>();
        coinMap.put("BTC/USDT", R.mipmap.app_icon_btc);
        coinMap.put("LTC/USDT", R.mipmap.app_icon_ltc);
        coinMap.put("EOS/USDT", R.mipmap.app_icon_eos);
        coinMap.put("ETC/USDT", R.mipmap.app_icon_etc);
        coinMap.put("ETH/USDT", R.mipmap.app_icon_eth);
//        coinMap.put("BCH/USDT", R.mipmap.app_icon_bch);
        mPresenter.getData("USDT", false);
        mPresenter.getBannerUrl();
        mPresenter.getNotice();
        mPresenter.getRMB();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCoin(StockCoinBean.StockProductVOBean stockSocketBean) {
        if (slimAdapter == null || slimAdapter.getData() == null || slimAdapter.getData().size() == 0)
            return;
        changePos = -1;
        Flowable.fromIterable(slimAdapter.getData())
                .filter(stockCoinBean -> stockCoinBean.getCode().equals(stockSocketBean.getCode()))
                .subscribe(stockCoinBean -> {
                    changePos = slimAdapter.getData().indexOf(stockCoinBean);
                });
        if (changePos != -1) {
            int i = changePos / 3;
            SlideCoinBean slideCoinBean = slideCoinBeans.get(i);
            switch (changePos % 3) {
                case 0:
                    slideCoinBean.setRateFirst(stockSocketBean.getChangeRate());
                    slideCoinBean.setUpFirst(stockSocketBean.isUp());
                    slideCoinBean.setUsdtFirst(stockSocketBean.getPrice());
                    break;
                case 1:
                    slideCoinBean.setRateSecond(stockSocketBean.getChangeRate());
                    slideCoinBean.setUpSecond(stockSocketBean.isUp());
                    slideCoinBean.setUsdtSecond(stockSocketBean.getPrice());
                    break;
                case 2:
                    slideCoinBean.setRateThird(stockSocketBean.getChangeRate());
                    slideCoinBean.setUpThird(stockSocketBean.isUp());
                    slideCoinBean.setUsdtThird(stockSocketBean.getPrice());
                    break;
            }
            updateSlideCoin(slideCoinBean, integerViewHashMap.get(i));
        }


        if (slimAdapter != null) {
            Flowable.fromIterable(slimAdapter.getData())
                    .filter(item -> item.getStockProductVO().getCode().equals(stockSocketBean.getCode()))
                    .subscribe(item -> {
                        stockSocketBean.setLight(true);
                        item.setStockProductVO(stockSocketBean);
                        slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(item), 1);
                        DisposUtil.close(timeMap.get(item.getStockProductVO().getCode()));
                        Disposable subscribe = Flowable.timer(600, TimeUnit.MILLISECONDS)
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(i -> {
                                    item.getStockProductVO().setLight(false);
                                    slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(item), 1);
                                });
                        timeMap.put(item.getStockProductVO().getCode(), subscribe);
                    }, e -> {
                    });
        }
    }

    private void initRecy() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        slimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_hangqing, new SlimInjector<StockCoinBean>() {
            @Override
            public void onInject(StockCoinBean data, IViewInjector injector, List payloads) {
                if (payloads == null || payloads.size() == 0) {
                    injector
                            .image(R.id.ivCoin, coinMap.get(data.getCode()) == null ? R.mipmap.app_icon_btc : coinMap.get(data.getCode()));

                }
                injector
                        .text(R.id.tvCoinName, data.getCode().substring(0, data.getCode().indexOf("/")))
                        .text(R.id.tvRate, data.getStockProductVO().getChangeRate())
                        .text(R.id.tvUSDT, String.format("USDT %s", CommonUtil.dealCoin(data.getStockProductVO().getPrice())))
                        .text(R.id.tvCNY, String.format("≈%s CNY", CommonUtil.dealCNY(data.getStockProductVO().getCnyPrice())))
                        .background(R.id.tvRate, ContextCompat.getDrawable(App.INSTANCE, data.getStockProductVO().isUp() ? R.drawable.app_shape_corner30_ff3 : R.drawable.app_shape_corner30_05c))
                        .textColor(R.id.tvUSDT, data.getStockProductVO().isLight() ?
                                (getResources().getColor(data.getStockProductVO().isUp() ? R.color.app_f53 : R.color.app_05c)) :
                                getResources().getColor(R.color.app_1d2));
                ;
            }
        }).attachTo(recyclerView).updateData(new ArrayList());

        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    ARouter.getInstance().build(RConfig.APP_MARKET_NEW).withString(Constans.CODE, slimAdapter.getDataItem(position).getCode()).navigation();
                });
    }

    /**
     * 接口回调，显示Banner图
     */
    public void showBanner(Banner bannerIamge) {
        isBannerShow = true;
        String value = bannerIamge.getValue();  // 获取Banner图地址
        String[] valueImage = value.split(",");

        String urlValue = bannerIamge.getUrlValue();  // Banner图点击的URL链接跳转
        if (!TextUtils.isEmpty(urlValue)) {
            valueUrl = urlValue.split(",");
        }
        for (int i = 0; i < valueImage.length; i++) {
            images.add(HttpConfig.BASE_IMG_URL + valueImage[i]);
        }
        if (banner == null)
            return;
        banner.setImages(images);
        banner.start();

    }

    public void setNotice(List<NoticeList> notice) {
        if (tvNotice != null) {
            if (notice.size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .onBackpressureDrop()
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                noticeList = notice.get((int) (i % notice.size()));
                                tvShowPosition.setText(String.valueOf(i % notice.size() + 1) + "/" + notice.size());
                                tvNotice.setText(noticeList.getTitle());
                                ClickUtil.click(tvNotice, () -> {
                                    ARouter.getInstance().build(RConfig.APP_MSG_DETAIL).withString(Constans.ID, noticeList.getId()).navigation();
                                });
                            }
                        }, System.out::println);
            }
        }
    }

    public void updateCoin(List<StockCoinBean> data) {
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }

        slimAdapter.updateData(data);
        slideCoinBeans = new ArrayList<>();

        for (int i = 0; i < data.size(); i++) {
            switch (i % 3) {
                case 0:
                    slideCoinBean = new SlideCoinBean(data.get(i).getCode(), "", "");
                    slideCoinBeans.add(slideCoinBean);
                    slideCoinBean.setRateFirst(data.get(i).getStockProductVO().getChangeRate());
                    slideCoinBean.setUpFirst(data.get(i).getStockProductVO().isUp());
                    slideCoinBean.setUsdtFirst(data.get(i).getStockProductVO().getPrice());
                    break;
                case 1:
                    slideCoinBean.setTypeSecond(data.get(i).getCode());
                    slideCoinBean.setRateSecond(data.get(i).getStockProductVO().getChangeRate());
                    slideCoinBean.setUpSecond(data.get(i).getStockProductVO().isUp());
                    slideCoinBean.setUsdtSecond(data.get(i).getStockProductVO().getPrice());
                    break;
                case 2:
                    slideCoinBean.setTypeThird(data.get(i).getCode());
                    slideCoinBean.setRateThird(data.get(i).getStockProductVO().getChangeRate());
                    slideCoinBean.setUpThird(data.get(i).getStockProductVO().isUp());
                    slideCoinBean.setUsdtThird(data.get(i).getStockProductVO().getPrice());
                    break;
            }
        }
        for (int i = 0; i < slideCoinBeans.size(); i++) {
            updateSlideCoin(slideCoinBeans.get(i), integerViewHashMap.get(i));
        }
//        bannerCoin.setImages(slideCoinBeans);
//        bannerCoin.start();
    }

    public void refreshFail() {
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }
    }

    public void updateRMB(String data) {
        tvRMB.setText(String.format("参考价格：%sCNY/USDT", data));
    }
}
